package com.example.simin_manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.simin_manage.admim.dto.Response;
import com.example.simin_manage.entity.OrderRecord;
import com.example.simin_manage.entity.PerformancePeriod;
import com.example.simin_manage.entity.SysUser;
import com.example.simin_manage.mapper.OrderMapper;
import com.example.simin_manage.mapper.PerformancePeriodMapper;
import com.example.simin_manage.mapper.SysUserMapper;
import com.example.simin_manage.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/9/14
 */
@RestController
@RequestMapping("/api/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private PerformancePeriodMapper performancePeriodMapper;
    @Autowired
    private OrderMapper orderMapper;


//用户添加单量
    @PostMapping("/add")
    public Response addOrder(@RequestBody OrderRecord order) {
        return orderService.addOrder(order);
    }
//查看所有单量并且绘制折线图
    @GetMapping("/list")
    public Response listOrders(@RequestParam Long userId,
                               @RequestParam String startDate,
                               @RequestParam String endDate) {
        return orderService.listOrders(userId, startDate, endDate);
    }
// 薪资计算
    @GetMapping("/salary")
    public Response calculateSalary(@RequestParam Long userId,
                                    @RequestParam String startDate,
                                    @RequestParam String endDate) {
        return orderService.calculateSalary(userId, startDate, endDate);
    }
    //用户查看时段
    @GetMapping("/period/summary")
    public Response getPeriodSummary(@RequestParam Long userId) {
        //  用户校验
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            return new Response(404, "用户不存在", null);
        }
        Integer dailyTarget = user.getDailyTarget() == null ? 0 : user.getDailyTarget();

        //  找到当前绩效周期（startDate <= today <= endDate）
        LocalDate today = LocalDate.now();
        PerformancePeriod currentPeriod = performancePeriodMapper.selectOne(
                new LambdaQueryWrapper<PerformancePeriod>()
                        .le(PerformancePeriod::getStartDate, today)
                        .ge(PerformancePeriod::getEndDate, today)
        );
        if (currentPeriod == null) {
            return new Response(404, "当前没有绩效周期", null);
        }

        // 3统计该周期内的总单量（把每天的 order_count 相加）
        Object sumObj = orderMapper.selectObjs(
                new QueryWrapper<OrderRecord>()
                        .select("SUM(order_count)")
                        .eq("user_id", userId)
                        .ge("record_date", currentPeriod.getStartDate())
                        .le("record_date", currentPeriod.getEndDate())
        ).stream().findFirst().orElse(null);

        int totalOrders = 0;
        if (sumObj != null) {
            totalOrders = ((Number) sumObj).intValue();
        }

        // 计算工作日天数（排除周六周日）
        long workDays = getWorkDays(currentPeriod.getStartDate(), currentPeriod.getEndDate());

        //计算目标总量与完成率（目标总量 = dailyTarget * 工作日天数）
        int targetTotal = dailyTarget * (int) workDays;
        double completionRate = targetTotal > 0 ? (double) totalOrders / targetTotal : 0.0;

        // 返回结果
        Map<String, Object> data = new HashMap<>();
        data.put("periodId", currentPeriod.getId());
        data.put("periodName", currentPeriod.getName());
        data.put("startDate", currentPeriod.getStartDate());
        data.put("endDate", currentPeriod.getEndDate());
        data.put("workDays", workDays);
        data.put("totalOrders", totalOrders);
        data.put("targetTotal", targetTotal);
        data.put("completionRate", String.format("%.2f%%", completionRate * 100));

        return new Response(200, "获取成功", data);
    }

    // 工作日计算辅助方法
    private long getWorkDays(LocalDate start, LocalDate end) {
        long days = 0;
        LocalDate d = start;
        while (!d.isAfter(end)) {
            DayOfWeek dow = d.getDayOfWeek();
            if (dow != DayOfWeek.SATURDAY && dow != DayOfWeek.SUNDAY) {
                days++;
            }
            d = d.plusDays(1);
        }
        return days;
    }


//组长 查看时段
    @GetMapping("/leader/summary")
    public Response leaderSummary(
            @RequestParam Long deptId,
            @RequestParam(required = false) Long periodId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate
    ) {
        // 找到该部门的所有用户
        List<SysUser> users = userMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getDeptId, deptId));

        if (users.isEmpty()) {
            return new Response(404, "该部门没有成员", null);
        }

        LocalDate start = null, end = null;

        // 如果传了 periodId，则按周期统计
        if (periodId != null) {
            PerformancePeriod p = performancePeriodMapper.selectById(periodId);
            if (p == null) {
                return new Response(404, "未找到周期", null);
            }
            start = p.getStartDate();
            end = p.getEndDate();
        }
        // 如果传了 startDate 和 endDate，则自定义时间
        else if (startDate != null && endDate != null) {
            start = LocalDate.parse(startDate);
            end = LocalDate.parse(endDate);
        }
        // 默认：最近7天
        else {
            end = LocalDate.now();
            start = end.minusDays(6);
        }

        long days = ChronoUnit.DAYS.between(start, end) + 1;

        List<Map<String, Object>> result = new ArrayList<>();

        for (SysUser user : users) {
            Integer total = orderMapper.selectObjs(
                    new QueryWrapper<OrderRecord>()
                            .select("SUM(order_count)")
                            .eq("user_id", user.getId())
                            .ge("record_date", start)
                            .le("record_date", end)
            ).stream().map(obj -> obj == null ? 0 : ((Number) obj).intValue()).findFirst().orElse(0);

            int dailyTarget = user.getDailyTarget() == null ? 0 : user.getDailyTarget();
            int targetTotal = dailyTarget * (int) days;
            double completionRate = targetTotal > 0 ? (double) total / targetTotal : 0;

            Map<String, Object> item = new HashMap<>();
            item.put("userId", user.getId());
            item.put("username", user.getUsername());
            item.put("nickname", user.getNickname());
            item.put("totalOrders", total);
            item.put("targetTotal", targetTotal);
            item.put("completionRate", String.format("%.2f", completionRate * 100) + "%");

            result.add(item);
        }

        return new Response(200, "获取成功", result);
    }






}
